class MediaController < ApplicationController
layout "default"
before_filter :initvars
before_filter :login_required, :only => [:new,:create,:edit,:update,:destroy,:listpages,:listadmin,:newpage,:upload]
before_filter :dnsbl_check
   
verify :method => :post, :only => [ :destroy, :create, :update,:upload_file ],
         :redirect_to => { :action => :list }


  def index
    if User.count==0
      redirect_to :controller=>"account",:action=>"signup"
    else
      redirect_to :action => 'list'
    end
  end

  def list
    if User.count==0
      redirect_to :controller=>"account",:action=>"signup"
    else
      @medias=Media.find(:all,:include=>:comments,:order => "medias.creation DESC" ,:conditions => ["type_id=1 and medias.published=1 and ? >=publicationdate and ((?< expirationdate and expires='1') or expires='0')",Time.now,Time.now],:limit=>10)
    end
  end
  
  def listadmin
    @medias = Media.paginate :page => params[:page], :per_page => 20, :order => "medias.creation DESC"
    render :action => "listadmin", :layout=>"admin"
  end

  def listpages
    @medias = Media.paginate :page => params[:page], :per_page => 20, :order => "medias.creation DESC", :conditions=>"type_id=2"
    render :action => "listpages", :layout=>"admin"
  end

  def show	
    thetime=Time.now
    @media = Media.find(params[:id])
    if (@media.publicationdate==nil ? @media.creation : @media.publicationdate) > thetime or ((@media.expires==1) and (thetime > (@media.expirationdate==nil ? Time.now.next_year : @media.expirationdate)))
	render :action => 'outofdate'
    end
  end

  def new
    @settings=session[:loadedsettings]
    @categories=Category.find(:all)
	if @categories.size>0
      @media = Media.new
      render :action=>"new", :layout=>"admin"
	else
	  params["msg"]=_("No category available! please create one.")
      render :action=>"error"
	end		
  end

  def newpage
    @settings=Setting.find(:first)
    @categories=Category.find(:all)
    @media = Media.new
    render :action=>"newpage", :layout=>"admin"
  end

  def create
    @media = Media.new(params[:media])
    @media.creation=Time.now
    @media.modification=Time.now
    @media.user_id=session[:user][:id]
    @media.permalink=Media.setpermalink(@media.title)
    @media.title=CGI.escapeElement(HTMLEntities.encode_entities(@media.title,:hexadecimal),"script")
    @media.text=CGI.escapeElement(HTMLEntities.encode_entities(@media.text,:named),"script")
    if @media.save
      @media.tag_with(params[:form]["tags"].to_s)     
      expire_fragment(%r{list*})
      if @media.type_id==1
        redirect_to :action => 'list'
      else
        redirect_to :action => 'show', :id => @media
      end
    else
      @categories=Category.find(:all)
      render :action => 'new', :layout=>"admin"
    end
  end

  def edit
    @categories=Category.find(:all)
    @media = Media.find(params[:id])
    render :action=>"edit", :layout=>"admin"
  end

  def update
    @media = Media.find(params[:id])
    @media.modification=Time.now
    params[:media]["title"]=CGI.escapeElement(HTMLEntities.encode_entities(params[:media]["title"],:hexadecimal),"script")
    params[:media]["text"]=CGI.escapeElement(HTMLEntities.encode_entities(params[:media]["text"],:named),"script")
    if @media.update_attributes(params[:media])
      expire_fragment(%r{list*})
      expire_fragment(%r{show/#{params[:id]}.*})
      @media.tag_with(params[:form]["tags"].to_s)
      redirect_to :action => 'show', :id => @media
    else
      render :action => 'edit'
    end
  end

  def destroy
    Media.find(params[:id]).destroy
    expire_fragment(%r{list*})
    expire_fragment(%r{show/#{params[:id]}.*})
    redirect_to :action => 'list'
  end
  
  def permalink
    @st="media/"+params[:year]+"/"+params[:month]+"/"+params[:day]+"/"+params[:title]
    @result = Media.find_by_permalink(@st)
    if @result!=nil
      redirect_to :action => 'show', :id => @result.id
    else
      flash[:notice]="Page non trouv&eacute;e" 
      redirect_to :action => 'list'
    end
  end
  
  def show_category
    thetime=Time.now
    @cat=Category.find_by_name(params[:cat])
    @medias=Media.find(:all,:include=>:comments,:order => "medias.creation DESC" ,:conditions => ["category_id= ? and medias.published=1 and ? >=publicationdate and ((?< expirationdate and expires='1') or expires='0')",@cat.id,thetime,thetime])
  end
  
  def show_tag
    thetime=Time.now
    thetag=params[:tag]
    @medias=Media.find_by_sql("SELECT distinctrow medias.* FROM `medias`,`taggings`,`tags` WHERE medias.id=taggings.taggable_id and tags.id=taggings.tag_id and tags.name=#{Media.quote(thetag)} and published=1 and #{Media.quote(thetime)} >=publicationdate and ((#{Media.quote(thetime)}< expirationdate and expires='1') or expires='0')")
  end
  
  def save(file)
    if (file['name']==nil) or (file['name']=="")
    	file['name']=file['picture'].original_filename
    end
    file['name']=sanitize_filename(file['name'])
    if ([".png",".jpg",".gif",".bmp"].include? File.extname(file['name']).to_s)
      File.open("#{RAILS_ROOT}/public/uploads/#{file['name']}", "w") { |f| f.write(file['picture'].read) }
      return file['name']
    else 
	return ""
    end
  end
  
  def sanitize_filename(value)
        just_filename = value.gsub(/^.*(\\|\/)/, '')
        @filename = just_filename.gsub(/[^\w\.\-]/,'_') 
	return @filename
  end
  
  def rss
	thetime=Time.now
    @headers["Content-Type"] = "application/xml; charset=utf-8" 
    @medias = Media.find(:all,:order =>"creation desc",:limit => 10, :conditions=>"published=1 and type_id=1 and '#{thetime}' >=publicationdate and (('#{thetime}'< expirationdate and expires='1') or expires='0')")
    render :action=>"rss",:layout=>false
  end
  
  def preview    
    @content = params[:text]
    @thetitle = params[:title]
    render :partial => "preview"
  end
  
  def listfiles
    @files=Dir["public/uploads/*.*"]
    render :action => "listfiles", :layout=>"admin"
  end
  
  def error
     
  end
  
  def search
     render :text=>"search result"
  end

  def find_by_date
    thetime=Time.now
    thedate=params[:year].to_s+"-"+params[:month].to_s+"%"
    @medias = Media.paginate :page => params[:page], :per_page => 20,:include=>:comments, :order => "medias.creation DESC", :conditions=>["type_id=1 and medias.published=1 and medias.creation like ? and ? >=publicationdate and ((?< expirationdate and expires='1') or expires='0')",thedate,thetime,thetime]
    render :action => "show_date"
  end
  
  def upload
    render :action=>"upload", :layout=>"admin"
  end

  def upload_file
    @result = save(params["file"])
    render :inline => "<img src='#{@settings.url}/uploads/#{@result.to_s}'><br/>Link:<a href='#{@settings.url}/uploads/#{@result.to_s}'>#{@result.to_s}</a><br/><br/><a href='/media/upload'>Back</a>", :layout => "admin"
  end
  
  def update_tags
    @newvalue=(params[:tag]+" "+params[:list]).split(' ').uniq.join(" ")
    render :partial => "update_tags"
  end  
	
end
